package com.erp.dao.impl;

import com.erp.bean.Department;
import com.erp.dao.DepartmentDao;
import com.erp.util.db.DataBaseDao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lyb
 * 部门数据访问接口实现类
 */
public class DepartmentDaoImpl extends DataBaseDao implements DepartmentDao {
    @Override
    public List<Department> findAll() {
        List<Department> list=new ArrayList<>();
        try {
            //获取数据库连接对象
            buildConnection();
            String sql="select did,dname from department";
            pstmt=conn.prepareStatement(sql);
            rs=pstmt.executeQuery();
            while (rs.next()){
                Department department=new Department(rs.getInt(1),rs.getString(2));
                list.add(department);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            close();
        }

        return list;
    }

    @Override
    public Department findById(int did) {
        Department department=null;
        try {
            //获取数据库连接对象
            buildConnection();
            String sql="select did,dname from department where did=? ";
            pstmt=conn.prepareStatement(sql);
            pstmt.setInt(1,did);
            rs=pstmt.executeQuery();
            while (rs.next()){
                department=new Department(rs.getInt(1),rs.getString(2));

            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            close();
        }

        return department;
    }

    @Override
    public int update(Department department) {
        int i=0;
        try {
            //获取数据库连接对象
            buildConnection();
            String sql="update department set dname=? where did=?";
            pstmt=conn.prepareStatement(sql);
            pstmt.setString(1,department.getDname());
            pstmt.setInt(2,department.getDid());
            i=pstmt.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            close();
        }

        return i;
    }

    @Override
    public int add(Department department) {
        int i=0;
        try {
            //获取数据库连接对象
            buildConnection();
            //创建sql语句
            String sql="insert into department (dname) values (?)";
            //预编译
            pstmt=conn.prepareStatement(sql);
            //设置参数
            pstmt.setString(1,department.getDname());
            i=pstmt.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            findAll();
        }
        return i;
    }
}
